package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Service
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 清理缓存数据
     * @param pattern
     */
    private void cleanCache(String pattern){
        Set keys = redisTemplate.keys(pattern);
        redisTemplate.delete(keys);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public Result list(Integer categoryId) {
        //1.非空判断
        if (categoryId == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.调用Mapper层，根据分类id查询菜品
        List<Dish> dishList = dishMapper.dishByCategoryId(categoryId);

        return Result.success(dishList);
    }

    /**
     * 菜品起售停售
     *
     * @param status
     * @return
     */
    @Transactional
    @Override
    public Result startOrClose(Integer status, Long id) {
        //1.非空判断
        if (status == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.设置菜单的状态
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        //3.如果菜品停售，关联的套餐状态停售
        if (status == StatusConstant.DISABLE) {
            ArrayList<Long> dishId = new ArrayList<>();
            dishId.add(id);
            List<Long> setmealByDishId = setmealDishMapper.getSetmealByDishId(dishId);
            if (setmealByDishId.size() > 0 && setmealByDishId != null) {
                for (Long setmealId : setmealByDishId) {
                    Setmeal setmeal = Setmeal.builder()
                            .status(StatusConstant.DISABLE)
                            .id(setmealId)
                            .build();
                    setmealMapper.update(setmeal);
                }
            }
        }

        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");

        return Result.success();
    }

    /**
     * 修改菜品
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    @Override
    public Result update(DishDTO dishDTO) {
        //1.非空判断
        if (dishDTO.getId() == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.拷贝属性 dishDTO 到dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //3.修改菜品
        dishMapper.update(dish);
        //3.删除关联的口味
        dishFlavorMapper.deleteDishFlavor(Arrays.asList(dish.getId()));
        //4.获取修改菜品id的口味id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            //5.批量添加口味
            dishFlavorMapper.batchAdd(flavors);

        }

        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @Override
    public Result<DishVO> getById(Long id) {
        //1.非空判断
        if (id == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.根据id查询菜品
        Dish dish = dishMapper.getById(id);
        //3.根据菜品id查询口味
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //4.封装到vo
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);

        return Result.success(dishVO);
    }

    /**
     * 批量删除菜品
     *
     * @param ids
     * @return
     */
    @Transactional
    @Override
    public Result delete(List<Long> ids) {
        //1.非空判断
        if (ids == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        //2.判断是否起售，若是，则不能删除
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE) {
                return Result.error(MessageConstant.DISH_ON_SALE);
            }
        }
        //3.判断是否与套餐中间表有关联，是则不能删除
        List<Long> setmealId = setmealDishMapper.getSetmealByDishId(ids);
        if (setmealId != null && setmealId.size() > 0) {
            return Result.error(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //4.调用mapper删除菜品
        dishMapper.deleteDish(ids);
        //5.关联的口味也删除
        dishFlavorMapper.deleteDishFlavor(ids);

        //将所有的菜品缓存数据清理掉，所有以dish_开头的key
        cleanCache("dish_*");
        return Result.success();
    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public Result page(DishPageQueryDTO dishPageQueryDTO) {
        //非空判断，设置默认值
        if (dishPageQueryDTO.getPage() == null) {
            dishPageQueryDTO.setPage(0);
        }
        if (dishPageQueryDTO.getPageSize() == null) {
            dishPageQueryDTO.setPageSize(10);
        }

        //开始分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //调用mapper分页查询
        Page<DishVO> dtoPage = dishMapper.page(dishPageQueryDTO);

        //封装到pageResult
        PageResult pageResult = new PageResult(dtoPage.getTotal(), dtoPage.getResult());

        return Result.success(pageResult);
    }

    /**
     * 新增菜品
     *
     * @param dishDTO
     * @return
     */
    @Transactional
    @Override
    public Result add(DishDTO dishDTO) {
        //1.非空判断
        if (dishDTO.getName() == null) {
            return Result.error(MessageConstant.DISH_NOT_FOUND);
        }
        //2.拷贝属性，dishDTO 到 dish
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

        //3.调用菜品Mapper层新增
        dishMapper.add(dish);

        //4.获取关联的菜品口味id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
            //5.调用菜品口味的Mapper层批量插入
            dishFlavorMapper.batchAdd(flavors);
        }

        //清理缓存数据
        String key = "dish_" + dishDTO.getCategoryId();
        cleanCache(key);
        return Result.success();
    }



}
